import {
  _decorator,
  Component,
  EventMouse,
  find,
  Input,
  input,
  instantiate,
  Node,
  Prefab,
  Vec3
} from 'cc'
import { PlantType } from './../Global'
import { Plant } from '../Plant'
import { Cell } from './Cell'
const { ccclass, property } = _decorator

@ccclass('MouseManager')
export class MouseManager extends Component {
  private static _instance: MouseManager = null

  @property([Prefab])
  private plantPrefabArray: Prefab[] = []

  private currentPlant: Node

  // 获取实例
  public static get Instance(): MouseManager {
    return this._instance
  }

  protected onLoad(): void {
    // 确保全局只有一个实例
    if (MouseManager._instance == null) {
      MouseManager._instance = this
    } else {
      console.log('MouseManager is already exist')
      this.node.destroy()
    }
    input.on(Input.EventType.MOUSE_MOVE, this.onMousMove, this)
  }

  onMousMove(event: EventMouse) {
    // 获取鼠标的位置
    let mousePosition = event.getUILocation()
    // 创建三维坐标-坐标原点在中心
    let worldPosition = new Vec3(mousePosition.x - 640, mousePosition.y - 360, 0)
    // 设置当前植物的位置
    if (this.currentPlant != null) {
      this.currentPlant.setPosition(worldPosition)
    }
  }

  addPlant(plantType: PlantType, event: EventMouse): boolean {
    if (this.currentPlant != null) {
      return false
    }
    let plantPrefab = this.getPlantPrefab(plantType)
    if (plantPrefab == null) {
      console.log('要种植的植物不存在')
      return false
    }
    this.currentPlant = plantPrefab
    this.currentPlant.parent = find('Canvas/Game')
    let location = event.getUILocation()
    this.currentPlant.setPosition(new Vec3(location.x - 640, location.y - 360, 0))
    // 种植成功
    return true
  }

  getPlantPrefab(plantType: PlantType): Node {
    for (let i = 0; i < this.plantPrefabArray.length; i++) {
      let plantPrefab = this.plantPrefabArray[i]
      let plantNode = instantiate(plantPrefab)
      if (plantNode.getComponent(Plant).plantType == plantType) {
        return plantNode
      } else {
        plantNode.destroy()
      }
    }
    return null
  }

  onCellClick(cell: Cell): void {
    if (this.currentPlant == null) {
      return
    }
    // this.currentPlant.setPosition(cell.node.position)
    if (cell.addPlant(this.currentPlant)) {
      // 种植完成,释放当前植物对象
      this.currentPlant = null
    }
  }
}
